package com.sunshine.lnuplus.ui.activity

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.res.Configuration
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.*
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.adapter.ChooseWeekRecyclerAdapter
import com.sunshine.lnuplus.adapter.MainFragmentAdapter
import com.sunshine.lnuplus.base.BaseActivity
import com.sunshine.lnuplus.callback.LoadDataCallBack
import com.sunshine.lnuplus.internet.CheckUpdate
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.service.LoadBackgroundService
import com.sunshine.lnuplus.utils.*
import com.sunshine.lnuplus.view.ShortCut
import com.sunshine.lnuplus.viewModel.MainViewModel
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : BaseActivity() {

    private lateinit var viewModel: MainViewModel
    private var conn: ServiceConnection? = null
    private var timetableAdaper: ChooseWeekRecyclerAdapter? = null
    private var showBNB = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        init()
        initTheme()
        initView()
    }

    private fun init(){
        //防止后台清除导致二次进入闪退
        if(InitData.lessonList == null){
            startActivity(Intent(this, SplashActivity::class.java))
            finish()
        }
        UpdateWidgetUtils.updateWidgets(this)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        ShortCut.init(this)
    }

    private fun initTheme() {
        when(getTimetableTheme()){
            1 -> {
                if(isNight){
                    background.setImageDrawable(resources.getDrawable(R.color.primary_black))
                    StatusBarUtils.setStatusBarWithColor(this, Color.BLACK)
                }else{
                    background.setImageDrawable(resources.getDrawable(R.color.white))
                    StatusBarUtils.setStatusBarWithColor(this, Color.WHITE)
                    bottomNavigationView.setBackgroundColor(Color.TRANSPARENT)
                }
            }
            2 -> {
                val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.background)
                background.setImageBitmap(BlurBuilder.blur(this, bitmap,
                    (viewModel.getBackgroundMohu()/100.0 * 25).toFloat()
                ))
                StatusBarUtils.setStatusBarWithImage(this)
            }
            3 -> {
                loadBackground()
            }
            4 -> {
                BackgroundUtils.setUserBackground(this, background, viewModel.getBackgroundMohu())
                StatusBarUtils.setStatusBarWithImage(this)
            }
        }
    }

    private fun initView() {
        //导航栏沉浸
        if(viewModel.getNavigationChenJin()) {
            setNavigation()
        }
        setNoTitle()
        //要先调用offscreenPageLimit否则already add csdn
        main_viewPager.offscreenPageLimit = 3
        main_viewPager.adapter = MainFragmentAdapter(supportFragmentManager)
        bottomNavigationView.setOnNavigationItemSelectedListener {
            main_viewPager.currentItem =
                when(it.itemId){
                    R.id.main_today -> 0
                    R.id.main_table -> 1
                    R.id.main_countdown -> 2
                    R.id.main_function -> 3
                    else -> 0
            }
            if(it.itemId == R.id.main_today){
                hideBNB()
            }
            else if(!showBNB){
                showBNB()
            }
            true
        }
        main_viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {}

            override fun onPageSelected(position: Int) {
                bottomNavigationView.menu.getItem(position).isChecked = true
                if(position == 0){
                    hideBNB()
                }
                else if(!showBNB){
                    showBNB()
                }
            }
        })
        if(viewModel.getDefaultScreen().toInt() == 1 && viewModel.isAutoToCountDown() && DateUtils.getThisWeek(
                InitData.lessonStyle.startMonth, InitData.lessonStyle.startDay) > InitData.lessonStyle.weekCount) {
            main_viewPager.currentItem = 2
        } else {
            if(viewModel.currentItem == 0 && !viewModel.firstStart){
                hideBNB()
            }
            if(viewModel.firstStart){
                main_viewPager.currentItem = viewModel.getDefaultScreen().toInt()
                if(main_viewPager.currentItem == 0) {
                    hideBNB()
                    viewModel.firstStart = false
                }
            }
        }

        if(viewModel.checkUpdate()){
            CheckUpdate(this, supportFragmentManager, false)
        }
    }

    private fun setNavigation(){
        StatusBarUtils.setNavigation(this)
        val height = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            50f,
            resources.displayMetrics
        ).toInt()
        if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT){
            val param = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, StatusBarUtils.getNavigationBarHeight(this) + height)
            param.bottomToBottom = 0
            bottomNavigationView.layoutParams = param
            bottomNavigationView.setPadding(0, 0, 0, height)
        }else{
            val param = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height)
            param.bottomToBottom = 0
            bottomNavigationView.layoutParams = param
            bottomNavigationView.setPadding(0, 0, 0, 0)
        }
    }

    //用于刷新课表
    fun setTimetableAdapter(adapter: ChooseWeekRecyclerAdapter){
        this.timetableAdaper = adapter
    }

    fun getTimetableAdapter() : ChooseWeekRecyclerAdapter?{
        return timetableAdaper
    }

    //隐藏底部栏
    fun hideBNB(){
        val outAnimator = ObjectAnimator.ofFloat(bottomNavigationView, "translationY", 0f, bottomNavigationView.height.toFloat())
        outAnimator.duration = 200
        outAnimator.start()
        object : Thread(){
            override fun run() {
                super.run()
                sleep(200)
                handler.sendEmptyMessage(2)
            }
        }.start()
        showBNB = false
    }

    fun showBNB(){
        bottomNavigationView.visibility = View.VISIBLE
        val inAnimator = ObjectAnimator.ofFloat(bottomNavigationView, "translationY", bottomNavigationView.height.toFloat(), 0f)
        inAnimator.duration = 200
        inAnimator.start()
        showBNB = true
    }

    //设置要显示的界面
    fun setCurrentItem(position: Int){
        main_viewPager.currentItem = position
    }

    private fun loadBackground() {
        if(BackgroundUtils.toGetBackground(this)){
            val intent = Intent(this, LoadBackgroundService::class.java)
            var loadBackgroundService: LoadBackgroundService

            BackgroundUtils.setBackground(
                this@MainActivity,
                background_everyday,
                true,
                viewModel.getBackgroundMohu()
            )
            StatusBarUtils.setStatusBarWithImage(this@MainActivity)

            conn = object : ServiceConnection {
                override fun onServiceDisconnected(name: ComponentName) {}
                override fun onServiceConnected(
                    name: ComponentName,
                    service: IBinder
                ) {
                    loadBackgroundService = (service as LoadBackgroundService.MyBind).getService
                    loadBackgroundService.setCallBack(object : LoadDataCallBack{
                        override fun onSuccess() {
                            handler.sendEmptyMessage(1)
                        }
                    })
                }
            }
            bindService(intent, conn!!, Service.BIND_AUTO_CREATE)
        }else {
            BackgroundUtils.setBackground(this@MainActivity, background_everyday, true, viewModel.getBackgroundMohu())
            StatusBarUtils.setStatusBarWithImage(this@MainActivity)
        }
    }

    @SuppressLint("HandlerLeak")
    val handler = object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (1 == msg.what){
                BackgroundUtils.setBackground(
                    this@MainActivity,
                    background_everyday,
                    false,
                    viewModel.getBackgroundMohu()
                )
                StatusBarUtils.setStatusBarWithImage(this@MainActivity)
                if(viewModel.getNavigationChenJin()) {
                    setNavigation()
                }
            }
            if(2 == msg.what){
                bottomNavigationView.visibility = View.GONE
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == TagHelper.MAIN){
            when(resultCode){
                TagHelper.APPSETTING -> {
                    startActivity(Intent(this, this.javaClass))
                    finish()
                }
            }
        }
    }

    override fun onPause() {
        super.onPause()
        viewModel.currentItem = main_viewPager.currentItem
    }

    override fun onDestroy() {
        super.onDestroy()
        if(conn != null){
            unbindService(conn!!)
            conn = null
        }
    }
}

